import EditForm from '@/pages/ApiFacade/components/EditForm';
import {
  addInterfaceInfoUsingPOST,
  deleteInterfaceInfoUsingPOST,
  listInterfaceInfoVOByPageUsingPOST, offlineUsingGET, onlineUsingGET,
  updateInterfaceInfoUsingPOST,
} from '@/services/api-backend/interfaceInfoController';
import {PlusOutlined} from '@ant-design/icons';
import type {ActionType, ProColumns, ProFormInstance} from '@ant-design/pro-components';
import {FooterToolbar, PageContainer, ProTable} from '@ant-design/pro-components';
import '@umijs/max';
import {Button, notification, Popconfirm} from 'antd';
import {SortOrder} from 'antd/lib/table/interface';
import React, {useRef, useState} from 'react';

const TableList: React.FC = () => {
  /**
   * @en-US Pop-up window of new window
   * @zh-CN 新建窗口的弹窗
   *  */
  /**
   * @en-US The pop-up window of the distribution update window
   * @zh-CN 分布更新窗口的弹窗
   * */
  const [showDetail, setShowDetail] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<API.BaseResponsePageInterfaceInfoVO>();
  const [selectedRowsState, setSelectedRows] = useState<API.DeleteRequest[]>([]);

  const [open, setOpen] = useState<boolean>(false);
  // 用户操作， add or update 默认add
  const [isAdd, setIsAdd] = useState<boolean>(true);

  const submit = async (values: API.InterfaceInfoAddRequest | API.InterfaceInfoEditRequest) => {
    try {
      const res = isAdd
        ? await addInterfaceInfoUsingPOST(values)
        : await updateInterfaceInfoUsingPOST({
          id: currentRow?.id,
          ...values,
        });
      if (res.data) {
        notification.success({
          message: '提示',
          description: '操作成功',
        });
        setOpen(false);
        // 重置表单
        actionRef.current?.reloadAndRest?.();
      }
    } catch (e) {
    }
  };

  const cancel = () => {
    setOpen(false);
    // 重置表单
    actionRef.current?.reloadAndRest?.();
  };

  /**
   * @en-US International configuration
   * @zh-CN 国际化配置
   * */
  const columns: ProColumns<API.BaseResponsePageInterfaceInfoVO>[] = [
    {
      title: '接口名称',
      dataIndex: 'name',
      tip: 'The rule name is the unique key',
      render: (dom, entity) => {
        return (
          <a
            onClick={() => {
              setCurrentRow(entity);
              setShowDetail(true);
            }}
          >
            {dom}
          </a>
        );
      },
      copyable: true,
      disable: true
    },
    {
      title: '接口地址',
      dataIndex: 'url',
      copyable: true,
      disable: true
    },
    {
      title: '描述',
      dataIndex: 'description',
      valueType: 'textarea',
      hideInSearch: true,
    },
    {
      //   GET,HEAD,POST,PUT,PATCH,DELETE,OPTIONS,TRACE 0 - 7
      title: '请求方法',
      dataIndex: 'requestMethod',
      filters: true,
      onFilter: true,
      valueEnum: {
        GET: {
          text: 'GET',
          status: 'Default',
        },
        HEAD: {
          text: 'HEAD',
          status: 'Processing',
        },
        POST: {
          text: 'POST',
          status: 'Default',
        },
        PUT: {
          text: 'PUT',
          status: 'Processing',
        },
        PATCH: {
          text: 'PATCH',
          status: 'Default',
        },
        DELETE: {
          text: 'DELETE',
          status: 'Processing',
        },
        OPTIONS: {
          text: 'OPTIONS',
          status: 'Default',
        },
        TRACE: {
          text: 'TRACE',
          status: 'Processing',
        },
      },
    },
    {
      title: '请求参数',
      dataIndex: 'requestParams',
      hideInTable: true,
      hideInSearch: true,
      valueType: 'textarea',
    },
    {
      title: '请求头',
      dataIndex: 'requestHeader',
      hideInTable: true,
      hideInSearch: true,
      valueType: 'textarea',
    },
    {
      title: '响应头',
      dataIndex: 'responseHeader',
      hideInTable: true,
      hideInSearch: true,
      valueType: 'textarea',
    },
    {
      title: '接口状态',
      dataIndex: 'status',
      valueType: 'select',
      valueEnum: {
        0: {
          text: '关闭',
          status: 'Error',
        },
        1: {
          text: '开启',
          status: 'success',
        },
      },
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      valueType: 'dateTime',
      hideInSearch: true,
      hideInForm: true,
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      valueType: 'dateTime',
      hideInSearch: true,
      hideInForm: true,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <a
          key="config"
          onClick={() => {
            setOpen(true);
            setIsAdd(false);
            setCurrentRow(record);
          }}
        >
          详情
        </a>,
      ],
    },
  ];
  return (
    <PageContainer>
      {/* 查询 */}
      <ProTable<API.BaseResponsePageInterfaceInfoVO, API.InterfaceInfoQueryRequest>
        headerTitle={'查询表格'}
        actionRef={actionRef}
        type={'table'}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        request={async (
          params: API.InterfaceInfoQueryRequest,
          sort: Record<string, SortOrder>,
          filter: Record<string, (string | number)[] | null>,
        ) => {
          const res = await listInterfaceInfoVOByPageUsingPOST(params);
          if (res.data) {
            return {
              data: res.data.records,
              success: true,
              total: res.data.total,
            };
          }
          return undefined;
        }}
        columns={columns}
      />
      <EditForm
        isAdd={isAdd}
        open={open}
        onCancel={cancel}
        onSubmit={submit}
        currentRow={currentRow}
      />

      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              已选择{' '}
              <a
                style={{
                  fontWeight: 600,
                }}
              >
                {selectedRowsState.length}
              </a>{' '}
              项 &nbsp;&nbsp;
            </div>
          }
        >
          <Popconfirm
            title="确定要删除?"
            key="del"
            onConfirm={async () => {
              if (!selectedRowsState) return;
              for (const e of selectedRowsState) {
                await deleteInterfaceInfoUsingPOST(e);
              }
              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
            }}
          >
            <Button>批量删除</Button>
          </Popconfirm>
        </FooterToolbar>
      )}
    </PageContainer>
  );
};
export default TableList;
